package com.kygeng.springframework.beans.factory.support;

import com.kygeng.springframework.beans.BeansException;
import com.kygeng.springframework.beans.factory.config.BeanDefinition;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;

/**
 * @Title: CglibSubclassingInstantiationStrategy
 * @Author: kygeng
 * @Package: com.kygeng.springframework.beans.factory.support
 * @Date: 2024/7/21 16:56
 * @Description: cglib实例化
 */
public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy {

    /**
     * 实例化
     *
     * @param beanDefinition
     * @param beanName
     * @param constructor
     * @param args
     * @return
     * @throws BeansException
     */
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor constructor, Object[] args) throws BeansException {

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(beanDefinition.getBeanClass());
        enhancer.setCallback(new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });
        //无构造函数实例化
        if (null == constructor) {
            return enhancer.create();
        }
        //有构造函数的实例化
        else {
            return enhancer.create(constructor.getParameterTypes(), args);
        }
    }
}
